import random
import sqlite3
from datetime import datetime

import requests

BASE_URL = 'http://10.34.192.10/oa/cxf/rest'


def getOnDuteFromDB(conn, user):
    p = (user[0],)
    for i in conn.execute('select * from dute where userid = ?', p):
        return i


def getUsersFromDB(conn):
    l = []
    for i in conn.execute('select * from user'):
        l.append(i)
    return l


def getUserToken(user):
    url = BASE_URL + '/api/login'
    payload = {'username': user[1], 'password': user[2]}
    r = requests.post(url, data=payload)
    token = r.json()['data']['token']
    return token


def onDute(user, dute, token):
    headers = {'token': token}
    url = BASE_URL + '/attend/insertAttendInfo'
    payload = {}
    now = datetime.now()
    minute = random.randint(15, 30)
    now = now.replace(hour=8, minute=minute)
    attend_time = now.strftime('%Y/%m/%d %H:%M:%S')
    payload['attendTime'] = attend_time
    payload["attendType"] = dute[1]
    payload["attendStatus"] = dute[2]
    payload["onworkTimeGap"] = dute[3]
    payload["offworkTimeGap"] = dute[4]
    payload["placeId"] = dute[5]
    payload["attendAddress"] = dute[6]
    payload["attendJd"] = dute[7]
    payload["attendWd"] = dute[8]
    payload["attendRemark"] = dute[9]
    response = requests.post(url, headers=headers, data=payload)
    if response.status_code == 200:
        return True
    else:
        return False


def daka(conn, user):
    if user[3] == 0:
        return
    token = getUserToken(user)
    dute = getOnDuteFromDB(conn, user)
    onDute(user, dute, token)


def main():
    conn = sqlite3.connect('daka.db')
    userlist = getUsersFromDB(conn)
    for i in userlist:
        daka(conn, i)


if __name__ == '__main__':
    main()
